import notebooks from '@/apis/notebooks'
import { Message } from 'element-ui'
const state = {
    notebooksList: null,
    curBookId:null,
    
}
const getters = {
    notebooksList: state => state.notebooksList || [],
    curNotebook: state => {
        if(!Array.isArray(state.notebooksList)) return {}
        if(!state.curBookId) return state.notebooksList[0] || {}
        return state.notebooksList.find(notebook => notebook.id == state.curBookId) || {}
      }
}
const mutations={
    setNotebooks(state, payload) {

        state.notebooksList = payload.notebooks
        
    },
    addNotebook(state, payload) {
        state.notebooksList.unshift(payload.notebook)
    },
    deleteNotebook(state, payload) {
       state.notebooksList=state.notebooksList.filter((notebook)=>notebook.id!=payload.notebookId)
    },
    updateNotebook(state, payload) {
        let notebook = state.notebooksList.find((notebook) => {
            return notebook.id == payload.notebookId;
        })
        
        notebook.title = payload.title;
   
    }
    ,
    setCurBook(state, payload) {
        state.curBookId = payload.curBookId
    }
}
const actions = {
    getNotebooks({ commit }) {
      
       return notebooks.getNotebookList().then((res) => {
            commit('setNotebooks',{notebooks:res.data})
        })
    },
    addNotebook({ commit }, payload) {
        return   notebooks.addNotebook({ title: payload.title }).then((res) => {
            commit('addNotebook', { notebook: res.data })
            Message.success(res.msg)
        })
    },
    updateNotebook({ commit }, payload) {
     return   notebooks.updateNotebook(payload.notebookId, { title: payload.title }).then((res) => {

            commit('updateNotebook', { notebookId: payload.notebookId, title: payload.title })
            Message.success(res.msg)
        })
    },
    deleteNotebook({ commit }, payload) {
    return  notebooks.deleteNotebook(payload.notebookId).then((res) => {
            commit('deleteNotebook', { notebookId: payload.notebookId })
            Message.success(res.msg)
        })
    }
    
}
export default {
    state,
    getters,
    mutations,
    actions,
}